package com.school.information.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.school.information.core.constant.CommonConstant;
import com.school.information.dto.UserDTO;
import com.school.information.entity.SysUserEntity;
import com.school.information.enums.result.SysResultEnum;
import com.school.information.enums.status.EnabledEnum;
import com.school.information.qo.SysUserQO;
import com.school.information.service.SysRoleService;
import com.school.information.service.SysUserService;
import com.school.information.utils.NumberUtil;
import com.school.information.utils.ResultUtil;
import com.school.information.utils.UserUtil;
import com.school.information.vo.UserListVO;
import com.school.information.vo.UserVO;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * (SysUser)表控制层
 *
 * @author ycc
 * @since 2023-05-28 23:28:42
 */
@Slf4j
@RestController
@RequestMapping("sysUser")
public class SysUserController {
    /**
     * 服务对象
     */
    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysRoleService roleService;

    @GetMapping("/currentUserInfo")
    public ResultUtil currentUserInfo() {
        // 当前登录用户信息
        SysUserEntity currentUser = UserUtil.getUser().getSysUser();
        SysUserEntity user = new SysUserEntity();
        user.setId(currentUser.getId());
        user.setRealName(currentUser.getRealName())
                .setGender(currentUser.getGender()).setAvatar(currentUser.getAvatar())
                .setPhone(currentUser.getPhone()).setEmail(currentUser.getEmail());
//        // 当前用户角色信息
//        Set<String> roles = roleService.findRoleByUserId(currentUser.getId());
//        // 权限集合
//        Set<String> permissions = menuService.findMenuByUserId(currentUser.getId());
        return ResultUtil.success(
                new UserVO().setUser(user).setRoles(UserUtil.getRoles()).setPermissions(UserUtil.getPerms())
        );
    }

    /**
     * 分页查询所有数据
     *
     * @return 所有数据
     */
    @PostMapping("/pageList")
    public ResultUtil pageList(@RequestBody SysUserQO sysUser) {
        IPage<SysUserEntity> page = sysUserService.pageList(sysUser);
        if (CollectionUtil.isEmpty(page.getRecords())) {
            return ResultUtil.success(page);
        }
        Set<Long> userIds = page.getRecords().stream().map(SysUserEntity::getUpdateUser).collect(Collectors.toSet());
        Map<Long, SysUserEntity> userMap = sysUserService.getUserMap(new ArrayList<>(userIds));
        List<UserListVO> list = new LinkedList<>();
        page.getRecords().forEach(item -> {
            UserListVO userListVO = new UserListVO();
            BeanUtils.copyProperties(item, userListVO);
            userListVO.setUpdateBy(userMap.get(item.getUpdateUser()).getRealName());
            list.add(userListVO);
        });
        IPage<UserListVO> resultPage = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
        resultPage.setRecords(list);
        return ResultUtil.success(resultPage);
    }

    /**
     * 根据id，查询用户信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public ResultUtil getById(@PathVariable("id") Long id) {
        if (NumberUtil.isNullOrLessEqual0(id)) {
            log.error("##参数错误，用户id不存在");
            return ResultUtil.ERROR_ARG;
        }
        SysUserEntity userInfo = sysUserService.getById(id);
        SysUserEntity user = new SysUserEntity();
        user.setId(userInfo.getId());
        user.setRealName(userInfo.getRealName()).setGender(userInfo.getGender())
                .setPhone(userInfo.getPhone()).setEmail(userInfo.getEmail())
                .setRemark(userInfo.getRemark());
        // 当前用户角色信息
        Set<Long> roleIds = roleService.findRoleIdByUserId(userInfo.getId());
        return ResultUtil.success(new UserVO().setUser(user).setRoleIds(roleIds));
    }

    /**
     * 新增用户信息
     *
     * @param userDTO
     * @return
     */
    @PostMapping("/save")
    public ResultUtil save(@RequestBody @Valid UserDTO userDTO) {
        log.info("##userDTO={}", userDTO);
        if (Objects.isNull(userDTO) || Objects.isNull(userDTO.getSysUser()) || CollectionUtils.isEmpty(userDTO.getRoleIds())) {
            log.error("##参数错误，用户信息数据为空");
            return ResultUtil.ERROR_ARG;
        }
        if (sysUserService.saveInfo(userDTO)) {
            return ResultUtil.success(CommonConstant.DEFAULT_PASSWORD);
        }
        log.error("##用户信息新增失败");
        return ResultUtil.error(SysResultEnum.ADD_USER_FAIL);
    }

    /**
     * 更新用户信息
     *
     * @param userDTO
     * @return
     */
    @PutMapping("/update")
    public ResultUtil update(@RequestBody @Valid UserDTO userDTO) {
        log.info("##userDTO={}", userDTO);
        if (Objects.isNull(userDTO) || Objects.isNull(userDTO.getSysUser()) || CollectionUtils.isEmpty(userDTO.getRoleIds())
                || NumberUtil.isNullOrLessEqual0(userDTO.getSysUser().getId())) {
            log.error("##参数错误，用户信息数据为空");
            return ResultUtil.ERROR_ARG;
        }
        if (sysUserService.updateInfo(userDTO)) {
            return ResultUtil.SUCCESS_NO_DATA;
        }
        log.error("##用户id={}更新失败", userDTO.getSysUser().getId());
        return ResultUtil.error(SysResultEnum.UPDATE_USER_FAIL);
    }

    /**
     * 启用用户
     *
     * @param id
     * @return
     */
    @PatchMapping("/enabled/{id}")
    public ResultUtil enabled(@PathVariable("id") Long id) {
        if (NumberUtil.isNullOrLessEqual0(id)) {
            log.error("##用户信息不存在");
            return ResultUtil.ERROR_ARG;
        }
        if (sysUserService.updateStatus(id, EnabledEnum.ENABLE)) {
            return ResultUtil.SUCCESS_NO_DATA;
        }
        return ResultUtil.error(SysResultEnum.ENABLED_USER_FAIL);
    }

    /**
     * 禁用用户
     *
     * @param id
     * @return
     */
    @PatchMapping("/disabled/{id}")
    public ResultUtil disabled(@PathVariable("id") Long id) {
        if (NumberUtil.isNullOrLessEqual0(id)) {
            log.error("##用户信息不存在");
            return ResultUtil.ERROR_ARG;
        }
        if (sysUserService.updateStatus(id, EnabledEnum.DISABLE)) {
            return ResultUtil.SUCCESS_NO_DATA;
        }
        return ResultUtil.error(SysResultEnum.DISABLED_USER_FAIL);
    }

    /**
     * 重置密码
     *
     * @return
     */
    @PatchMapping("/resetPwd/{id}")
    public ResultUtil resetPwd(@PathVariable("id") Long id) {
        if (NumberUtil.isNullOrLessEqual0(id)) {
            return ResultUtil.ERROR_ARG;
        }
        if (sysUserService.resetPwd(id)) {
            return ResultUtil.SUCCESS_NO_DATA;
        }
        return ResultUtil.error(SysResultEnum.RESET_PWD_FAIL);
    }

    /**
     * 删除用户信息
     *
     * @param ids
     * @return
     */
    @DeleteMapping("/{ids}")
    public ResultUtil delete(@PathVariable("ids") Long[] ids) {
        if (ArrayUtils.isEmpty(ids)) {
            return ResultUtil.ERROR_ARG;
        }
        if (sysUserService.removeByIds(Arrays.asList(ids))) {
            return ResultUtil.SUCCESS_NO_DATA;
        }
        log.error("##用户信息id={}删除失败", ids);
        return ResultUtil.error(SysResultEnum.DEL_USER_FAIL);
    }
}

